/**
 * Copyright &copy; 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
 */
package com.jeeplus.modules.tms.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.jeeplus.core.persistence.Page;
import com.jeeplus.core.service.CrudService;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.modules.tms.entity.Torder;
import com.jeeplus.modules.tms.mapper.TorderMapper;
import com.jeeplus.modules.tms.entity.OrderAddress;
import com.jeeplus.modules.tms.mapper.OrderAddressMapper;
import com.jeeplus.modules.tms.entity.OrderDetail;
import com.jeeplus.modules.tms.mapper.OrderDetailMapper;

/**
 * 订单Service
 * @author dhw
 * @version 2017-12-01
 */
@Service
@Transactional(readOnly = true)
public class TorderService extends CrudService<TorderMapper, Torder> {

	@Autowired
	private OrderAddressMapper orderAddressMapper;
	@Autowired
	private OrderDetailMapper orderDetailMapper;
	
	public Torder get(String id) {
		Torder torder = super.get(id);
		torder.setOrderAddressList(orderAddressMapper.findList(new OrderAddress(torder)));
		torder.setOrderDetailList(orderDetailMapper.findList(new OrderDetail(torder)));
		return torder;
	}
	
	public List<Torder> findList(Torder torder) {
		return super.findList(torder);
	}
	
	public Page<Torder> findPage(Page<Torder> page, Torder torder) {
		return super.findPage(page, torder);
	}
	
	@Transactional(readOnly = false)
	public void save(Torder torder) {
		super.save(torder);
		for (OrderAddress orderAddress : torder.getOrderAddressList()){
			if (orderAddress.getId() == null){
				continue;
			}
			if (OrderAddress.DEL_FLAG_NORMAL.equals(orderAddress.getDelFlag())){
				if (StringUtils.isBlank(orderAddress.getId())){
					orderAddress.setForeignId(torder);
					orderAddress.preInsert();
					orderAddressMapper.insert(orderAddress);
				}else{
					orderAddress.preUpdate();
					orderAddressMapper.update(orderAddress);
				}
			}else{
				orderAddressMapper.delete(orderAddress);
			}
		}
		for (OrderDetail orderDetail : torder.getOrderDetailList()){
			if (orderDetail.getId() == null){
				continue;
			}
			if (OrderDetail.DEL_FLAG_NORMAL.equals(orderDetail.getDelFlag())){
				if (StringUtils.isBlank(orderDetail.getId())){
					orderDetail.setForeignId(torder);
					orderDetail.preInsert();
					orderDetailMapper.insert(orderDetail);
				}else{
					orderDetail.preUpdate();
					orderDetailMapper.update(orderDetail);
				}
			}else{
				orderDetailMapper.delete(orderDetail);
			}
		}
	}
	
	@Transactional(readOnly = false)
	public void delete(Torder torder) {
		super.delete(torder);
		orderAddressMapper.delete(new OrderAddress(torder));
		orderDetailMapper.delete(new OrderDetail(torder));
	}
	
}